import axios from "axios";
import { ElMessage } from "element-plus";
import { getCookies, getLocalStorage, clearLoginInfo } from "@/utils/cache.js";
import router from "@/router";
const service = axios.create({
  baseURL: "/api/shop/admin",
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers = {
      "Content-Type": "application/json;charset=utf-8",
    };
    const token = getCookies("TOKEN");
    config.headers["platform"] = "seller";
    if (token) {
      config.headers["Authorization"] = token;
    }

    const user = getLocalStorage("USER_INFO");
    if (user && user.id) {
      config.headers["appId"] = user.id;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.success) {
      return response.data.result;
    } else {
      switch (response.data.resultCode) {
        case 12006:
        case 12005:
        case 12003:
          clearLoginInfo();
          ElMessage.warning(response.data.resultInfo || "登录失效,请重新登陆");
          router.push("/login");
          break;
        default:
          ElMessage.warning(response.data.resultInfo || "服务器异常,请联系管理员！");
          break;
      }
      return Promise.reject(response.data);
    }
  },
  (error) => {
    switch (error.response.status) {
      case 404:
        ElMessage.warning("未找到服务器资源!");
        break;
      default:
        ElMessage.warning("服务器异常,请联系管理员！");
        break;
    }
    return Promise.reject(error.response);
  }
);
export default service;
